package com.lollipop.synthential.list;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: J.K
 * @Date: 2020-11-10 13:22
 * @Description: List去重的5种方法
 */
public class ListDistinct {

    /**
     * 1.通过LinkedHashSet去重
     */
    public void LinkedHashSetMethod() {
        ArrayList<Integer> numbersList = new ArrayList<Integer>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));

        System.out.println(numbersList);

        LinkedHashSet<Integer> hashSet = new LinkedHashSet<Integer>(numbersList);

        ArrayList<Integer> listWithoutDuplicates = new ArrayList<Integer>(hashSet);

        System.out.println(listWithoutDuplicates);
    }

    /**
     * 2.通过Java8的Stream去重
     */
    public void StreamCollectorsMethod() {
        ArrayList<Integer> numbersList = new ArrayList<>(Arrays.asList(1, 1, 2, 3, 3, 3, 4, 5, 6, 6, 6, 7, 8));
        System.out.println(numbersList);

        List<Integer> listWithoutDuplicates = numbersList.stream().distinct().collect(Collectors.toList());
        System.out.println(listWithoutDuplicates);
    }

    /**
     * 3.通过HashSet去重
     *
     * @param list
     */
    public void HashSetMethod(List<String> list) {
        HashSet<String> set = new HashSet<String>(list.size());
        List<String> result = new ArrayList<String>(list.size());
        for (String str : list) {
            if (set.add(str)) {
                result.add(str);
            }
        }
        list.clear();
        list.addAll(result);
    }

    /**
     * 4.通过List的contains方法去重
     *
     * @param list
     */
    public void ListContainsMethod(List<String> list) {
        List<String> result = new ArrayList<String>(list.size());
        for (String str : list) {
            if (!result.contains(str)) {
                result.add(str);
            }
        }
        list.clear();
        list.addAll(result);
    }

    /**
     * 5.通过双for循环去重
     *
     * @param list
     */
    public void DoubleForMethod(List<String> list) {
        System.out.println(list);
        for (int i = 0; i < list.size(); i++) {
            for (int j = 0; j < list.size(); j++) {
                if (i != j && list.get(i) == list.get(j)) {
                    list.remove(list.get(j));
                }
            }
        }
        System.out.println(list);
    }
}
